import 'package:edu/constants/app_strings.dart';
import 'package:edu/pages/common/course_edu_cell_widget.dart';
import 'package:edu/pages/common/empty_content_widget.dart';
import 'package:edu/pages/main_tab/edu/edu_page_logic.dart';
import 'package:edu/pages/main_tab/main_tab_logic.dart';
import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/app_router.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:tuple/tuple.dart';

class EduPage extends StatefulWidget {
  const EduPage({super.key});

  @override
  State<EduPage> createState() => _EduPageState();

  // 激活的课程id
  static final activeCourseIdNotifier = ValueNotifier<int>(0);
}

class _EduPageState extends State<EduPage> {
  @override
  void initState() {
    super.initState();
    context.read<EduPageLogic>().init();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(context),
      body: _buildMainBody(context),
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    return AppBar(title: Text(AppStrings.learning));
  }

  Widget _buildMainBody(BuildContext context) {
    return Selector<EduPageLogic, bool>(
      selector: (context, logic) => logic.isContentEmpty,
      builder: (context, v, child) {
        if (v) {
          return Selector<EduPageLogic, Tuple2<bool, bool>>(
            selector: (context, logic) => Tuple2(logic.loading, logic.error),
            builder: (context, v, child) {
              return EmptyContentWidget(
                isLoading: v.item1,
                isError: v.item2,
                reloadAction: () {
                  context.read<EduPageLogic>().loadPurchasedCourses();
                },
                buttonTitle: AppStrings.noCourseGoFind,
                otherAction: () {
                  final mainTabLogic = context.read<MainTabLogic>();
                  mainTabLogic.setMainTabIndex(1);
                },
              );
            },
          );
        } else {
          return _buildCourseList(context);
        }
      },
    );
  }

  // 已订购的课程列表
  Widget _buildCourseList(BuildContext context) {
    return Selector<EduPageLogic, int>(
      selector: (context, logic) => logic.purchasedCourses.length,
      builder: (context, _, child) {
        final logic = context.read<EduPageLogic>();
        return ListView.builder(
          itemCount: logic.purchasedCourses.length,
          itemBuilder: (context, index) {
            final order = logic.purchasedCourses[index];
            return CourseEduCellWidget(
              course: order,
              onTap: () {
                context.pushNamed(
                  AppRouter.kEduCourse,
                  queryParameters: {'id': order.id.toString()},
                );
              },
            );
          },
        );
      },
    );
  }
}
